package com.tansty.service.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tansty.dao.mapper.OrdersMapper;
import com.tansty.dao.mapper.PetMapper;
import com.tansty.dao.mapper.UserMapper;
import com.tansty.pojo.dto.LineDTO;
import com.tansty.pojo.dto.OrderDTO;
import com.tansty.pojo.po.Orders;
import com.tansty.pojo.po.Pet;
import com.tansty.pojo.po.User;
import com.tansty.service.enums.Errors;
import com.tansty.service.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tansty
 * @since 2021-08-25
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    PetMapper petMapper;
    @Autowired
    UserMapper userMapper;
    @Override
    public List<OrderDTO> getAll() {
        return ordersMapper.getAll();
    }

    @Override
    public int updateOrder(OrderDTO orderDTO) {
        if(petMapper.selectOne(new QueryWrapper<Pet>().eq("name",orderDTO.getName()))==null){
            return Errors.NOT_FOUND_PET.getCode();
        }else if(userMapper.selectOne(new QueryWrapper<User>().eq("user_name",orderDTO.getUserName()))==null){
            return Errors.NOT_FOUND_USER.getCode();
        }
        return ordersMapper.updateOrder(orderDTO);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int addOrder(OrderDTO orderDTO) {
        Pet pet = petMapper.selectOne(new QueryWrapper<Pet>().eq("name", orderDTO.getName()));
        if(pet==null){
            return Errors.NOT_FOUND_PET.getCode();
        }else if(pet.getIsBuy()==1){
            return Errors.PET_IS_BUY.getCode();
        }else if(userMapper.selectOne(new QueryWrapper<User>().eq("user_name",orderDTO.getUserName()))==null){
            return Errors.NOT_FOUND_USER.getCode();
        }
        int code = ordersMapper.addOrder(orderDTO);
        pet.setIsBuy(1);
        petMapper.updateById(pet);
        return code ;
    }
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int deleteOrder(OrderDTO orderDTO) {
        Pet pet = petMapper.selectOne(new QueryWrapper<Pet>().eq("name", orderDTO.getName()));
        ordersMapper.deleteOrder(orderDTO);
        pet.setIsBuy(0);
        return petMapper.updateById(pet);
    }

    @Override
    public List<LineDTO> getLineData() {
        return ordersMapper.getLineData();
    }
}
